package com.sicnu.demo07

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.widget.Button
import android.widget.GridLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.sicnu.demo07.model.CardMatchingGame

class CardGameActivity : AppCompatActivity() {
    
    private lateinit var gridCards: GridLayout
    private lateinit var tvScore: TextView
    private lateinit var btnRestart: Button
    private lateinit var btnExit: Button
    
    private lateinit var game: CardMatchingGame
    private val cardButtons = mutableListOf<Button>()
    private val CARD_COUNT = 16
    private val handler = Handler(Looper.getMainLooper())
    private var isProcessing = false
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_card_game)
        
        initViews()
        initGame()
        setListeners()
    }
    
    private fun initViews() {
        gridCards = findViewById(R.id.gridCards)
        tvScore = findViewById(R.id.tvScore)
        btnRestart = findViewById(R.id.btnRestart)
        btnExit = findViewById(R.id.btnExit)
    }
    
    private fun initGame() {
        game = CardMatchingGame(CARD_COUNT)
        cardButtons.clear()
        gridCards.removeAllViews()
        isProcessing = false
        
        for (i in 0 until CARD_COUNT) {
            val button = Button(this).apply {
                text = ""
                textSize = 20f
                // 尝试使用drawable中的图片，如果没有则使用颜色
                try {
                    setBackgroundResource(R.drawable.card_back)
                } catch (e: Exception) {
                    setBackgroundColor(Color.LTGRAY)
                    text = getString(R.string.card_back)
                }
                setTextColor(Color.BLACK)
                gravity = Gravity.CENTER
                
                val params = GridLayout.LayoutParams().apply {
                    width = 0
                    height = 0
                    columnSpec = GridLayout.spec(i % 4, 1f)
                    rowSpec = GridLayout.spec(i / 4, 1f)
                    setMargins(4, 4, 4, 4)
                }
                layoutParams = params
                
                setOnClickListener {
                    onCardClick(i)
                }
            }
            
            cardButtons.add(button)
            gridCards.addView(button)
        }
        
        updateScore()
    }
    
    private fun onCardClick(index: Int) {
        if (isProcessing) return // 正在处理中，禁止点击
        
        val cardBefore = game.cardAtIndex(index)
        if (cardBefore.isMatched) return // 已匹配的卡片不能点击
        
        // 检查是否有已选中的卡片
        var hasChosenCard = false
        for (i in 0 until CARD_COUNT) {
            val c = game.cardAtIndex(i)
            if (c.isChosen && !c.isMatched && i != index) {
                hasChosenCard = true
                break
            }
        }
        
        game.chooseCardAtIndex(index)
        updateAllCardsUI()
        updateScore()
        
        // 如果之前有已选中的卡片，现在需要检查匹配结果
        if (hasChosenCard) {
            val cardAfter = game.cardAtIndex(index)
            // 如果这张卡片没有被匹配，说明匹配失败，需要延迟翻回
            if (!cardAfter.isMatched && !cardAfter.isChosen) {
                isProcessing = true
                handler.postDelayed({
                    updateAllCardsUI()
                    isProcessing = false
                }, 1000) // 1秒后翻回
            }
        }
    }
    
    private fun updateAllCardsUI() {
        for (i in 0 until CARD_COUNT) {
            updateCardUI(i)
        }
    }
    
    private fun updateCardUI(index: Int) {
        val card = game.cardAtIndex(index)
        val button = cardButtons[index]
        
        when {
            card.isMatched -> {
                button.text = card.toString()
                button.setBackgroundColor(Color.GREEN)
                button.setTextColor(Color.WHITE)
                button.isEnabled = false
            }
            card.isChosen -> {
                button.text = card.toString()
                button.setBackgroundColor(Color.parseColor("#FFA500")) // Orange
                button.setTextColor(Color.BLACK)
                button.isEnabled = !isProcessing
            }
            else -> {
                button.text = ""
                // 尝试使用drawable中的图片，如果没有则使用颜色和文字
                try {
                    button.setBackgroundResource(R.drawable.card_back)
                } catch (e: Exception) {
                    button.setBackgroundColor(Color.LTGRAY)
                    button.text = getString(R.string.card_back)
                }
                button.setTextColor(Color.BLACK)
                button.isEnabled = !isProcessing
            }
        }
    }
    
    private fun updateScore() {
        tvScore.text = game.score.toString()
    }
    
    private fun setListeners() {
        btnRestart.setOnClickListener {
            initGame()
        }
        
        btnExit.setOnClickListener {
            val resultIntent = Intent().apply {
                putExtra(MainActivity.EXTRA_HIGH_SCORE, game.score)
            }
            setResult(RESULT_OK, resultIntent)
            finish()
        }
    }
    
    override fun onBackPressed() {
        handler.removeCallbacksAndMessages(null) // 清除所有延迟任务
        val resultIntent = Intent().apply {
            putExtra(MainActivity.EXTRA_HIGH_SCORE, game.score)
        }
        setResult(RESULT_OK, resultIntent)
        super.onBackPressed()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null) // 清除所有延迟任务
    }
}

